﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPNETVN.PORTAL.Components.Helpers;
using ASPNETVN.PORTAL.Components.UI;
using ASPNETVN.PORTAL.Components.Share;
using CDTM.Modules.TraCuuDiem.Components;
using System.Collections;
using System.Data;

namespace CDTM.Modules.TraCuuDiem.Controls
{
    public partial class ItemManager : AddEditItemControl
    {
        private static DataSet _dsLop = null;
        private static DataSet _dsMaSV = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                GetLop();

                //GetLog();
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            this.ReturnToReferrerPage();
        }

        private void GetLop()
        {
            _dsLop = Lop.SelectAllLop();

            ddlClass.DataSource = _dsLop;
            ddlClass.DataBind();
        }

        #region LOG
        /*
        /// <summary>
        /// Lấy dữ liệu nhật ký.
        /// </summary>
        private void GetLog()
        {
            listLog = Log.SelectCollectionAll()
                .Where(x => x.TraCuuDiemType == Global.TraCuuDiemType.TaoMatKhau.ToString())
                .OrderByDescending(obj => obj.DateCreated).ToList();

            repLog.DataSource = listLog;
            repLog.DataBind();
        }

        protected void btnDelLog_Click(object sender, EventArgs e)
        {
            Log.DeleteLogDynamic("1=1");

            GetLog();
        }

        #region Log Paging
        public static List<Log> listLog;

        protected void PageDropDownList_SelectedIndexChanged(Object sender, EventArgs e)
        {
            DropDownList ddl = (DropDownList)sender;
            repLog.PageIndex = ddl.SelectedIndex;
            repLog.DataSource = listLog;
            repLog.DataBind();
        }

        protected void repLog_DataBound(object sender, EventArgs e)
        {
            if (repLog.Rows.Count > 0)
            {
                // Retrieve the pager row.
                GridViewRow bottomPagerRow = repLog.BottomPagerRow;
                GridViewRow topPagerRow = repLog.TopPagerRow;

                // Retrieve the DropDownList and Label controls from the row.
                DropDownList topPageList = (DropDownList)topPagerRow.Cells[0].FindControl("PageDropDownList");
                DropDownList bottomPageList = (DropDownList)bottomPagerRow.Cells[0].FindControl("PageDropDownList");
                Label topPageLabel = (Label)topPagerRow.Cells[0].FindControl("PageLabel");
                Label bottomPageLabel = (Label)bottomPagerRow.Cells[0].FindControl("PageLabel");

                if (topPageList != null && bottomPageList != null)
                {
                    for (int i = 0; i < repLog.PageCount; i++)
                    {
                        int pageNumber = i + 1;
                        ListItem item = new ListItem(pageNumber.ToString());
                        if (i == repLog.PageIndex)
                        {
                            item.Selected = true;
                        }

                        topPageList.Items.Add(item);
                        bottomPageList.Items.Add(item);
                    }
                }

                if (topPageLabel != null && bottomPageLabel != null)
                {
                    topPageLabel.Text = bottomPageLabel.Text = " / " + repLog.PageCount.ToString();
                }
            }
        }

        protected void repLog_PageIndexChanged(object sender, EventArgs e)
        {
            repLog.SelectedIndex = -1;
        }
        #endregion

        #region LogDetails Paging
        public static List<LogDetail> listLogDetails;

        protected void PageDropDownList2_SelectedIndexChanged(Object sender, EventArgs e)
        {
            DropDownList ddl = (DropDownList)sender;
            repLogDetails.PageIndex = ddl.SelectedIndex;
            repLogDetails.DataSource = listLogDetails;
            repLogDetails.DataBind();
        }

        protected void repLogDetails_DataBound(object sender, EventArgs e)
        {
            if (repLogDetails.Rows.Count > 0)
            {
                // Retrieve the pager row.
                GridViewRow bottomPagerRow = repLogDetails.BottomPagerRow;
                GridViewRow topPagerRow = repLogDetails.TopPagerRow;

                // Retrieve the DropDownList and Label controls from the row.
                DropDownList topPageList = (DropDownList)topPagerRow.Cells[0].FindControl("PageDropDownList2");
                DropDownList bottomPageList = (DropDownList)bottomPagerRow.Cells[0].FindControl("PageDropDownList2");
                Label topPageLabel = (Label)topPagerRow.Cells[0].FindControl("PageLabel2");
                Label bottomPageLabel = (Label)bottomPagerRow.Cells[0].FindControl("PageLabel2");

                if (topPageList != null && bottomPageList != null)
                {
                    for (int i = 0; i < repLogDetails.PageCount; i++)
                    {
                        int pageNumber = i + 1;
                        ListItem item = new ListItem(pageNumber.ToString());
                        if (i == repLogDetails.PageIndex)
                        {
                            item.Selected = true;
                        }

                        topPageList.Items.Add(item);
                        bottomPageList.Items.Add(item);
                    }
                }

                if (topPageLabel != null && bottomPageLabel != null)
                {
                    topPageLabel.Text = bottomPageLabel.Text = " / " + repLogDetails.PageCount.ToString();
                }
            }
        }

        protected void repLogDetails_PageIndexChanged(object sender, EventArgs e)
        {
            repLog.SelectedIndex = -1;
        }
        #endregion

        protected void repLog_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            HiddenField crl = (HiddenField)repLog.Rows[e.NewSelectedIndex].FindControl("hdfLogID");

            if (crl != null)
            {
                int logID = Convert.ToInt32(crl.Value);

                listLogDetails = LogDetail.SelectCollectionDynamic("LogID = " + logID, "");
                repLogDetails.DataSource = listLogDetails;
                repLogDetails.DataBind();
                pnlDetails.Visible = true;
            }
        }
        */
        #endregion

        protected void btnCreatePass_Click(object sender, EventArgs e)
        {
            try
            {
                //1. Lấy danh sách Mã sinh viên theo lớp.
                if (chkAllClass.Checked == true)
                    _dsMaSV = Lop.SelectQuyenAllLop();
                else
                    _dsMaSV = Lop.SelectQuyenByLop(ddlClass.SelectedValue);

                //2. Tạo và lưu mật khẩu tương ứng với mã Sinh viên. Mật khẩu = Mã hóa(Mã SV).
                List<QuyenDN> listQuyenDN = new List<QuyenDN>();
                if (_dsMaSV != null && _dsMaSV.Tables.Count > 0)
                {

                    //Lọc danh sách Mã SV chưa tạo
                    DataRow[] rows = _dsMaSV.Tables[0].Select("IsExists = 0");

                    for (int i = 0; i < rows.Length; i++)
                    {
                        QuyenDN quyen = new QuyenDN();
                        quyen.MaSV = rows[i]["MaSV"].ToString();
                        quyen.MatKhau = ASPNETVN.PORTAL.Components.Security.PortalSecurity.Encrypt(rows[i]["MaSV"].ToString());
                        quyen.DaKichHoat = false;

                        listQuyenDN.Add(quyen);
                    }

                    if (listQuyenDN.Count > 0)
                        QuyenDN.InsertUpdateCollection(listQuyenDN);
                }

                //3. Binding
                //Thông tin bao gồm các cột: IsExists, MaSV, Lop, DaKichHoat
                if (listQuyenDN.Count > 0)//Nếu có dữ liệu thêm mới -> Load lại dữ liệu
                {
                    if (chkAllClass.Checked == true)
                        _dsMaSV = Lop.SelectQuyenAllLop();
                    else
                        _dsMaSV = Lop.SelectQuyenByLop(ddlClass.SelectedValue);
                }

                gvCreatePass.DataSource = _dsMaSV;
                gvCreatePass.DataBind();

                pnlKichHoat.Visible = (gvCreatePass.Rows.Count > 0);
            }
            catch (Exception ex) { }
        }

        private void LoadDataCaretePass()
        {
            if (chkAllClass.Checked == true)
                _dsMaSV = Lop.SelectQuyenAllLop();
            else
                _dsMaSV = Lop.SelectQuyenByLop(ddlClass.SelectedValue);

            gvCreatePass.DataSource = _dsMaSV;
            gvCreatePass.DataBind();

            pnlKichHoat.Visible = (gvCreatePass.Rows.Count > 0);
        }

        #region GridView CreatePass Paging

        protected void PageDropDownListgvCreatePass_SelectedIndexChanged(Object sender, EventArgs e)
        {
            DropDownList ddl = (DropDownList)sender;
            gvCreatePass.PageIndex = ddl.SelectedIndex;
            gvCreatePass.DataSource = _dsMaSV;
            gvCreatePass.DataBind();
        }

        protected void gvCreatePass_DataBound(object sender, EventArgs e)
        {
            if (gvCreatePass.Rows.Count > 0)
            {
                // Retrieve the pager row.
                GridViewRow bottomPagerRow = gvCreatePass.BottomPagerRow;
                GridViewRow topPagerRow = gvCreatePass.TopPagerRow;

                // Retrieve the DropDownList and Label controls from the row.
                DropDownList topPageList = (DropDownList)topPagerRow.Cells[0].FindControl("PageDropDownListgvCreatePass");
                DropDownList bottomPageList = (DropDownList)bottomPagerRow.Cells[0].FindControl("PageDropDownListgvCreatePass");
                Label topPageLabel = (Label)topPagerRow.Cells[0].FindControl("PageLabelgvCreatePass");
                Label bottomPageLabel = (Label)bottomPagerRow.Cells[0].FindControl("PageLabelgvCreatePass");

                if (topPageList != null && bottomPageList != null)
                {
                    for (int i = 0; i < gvCreatePass.PageCount; i++)
                    {
                        int pageNumber = i + 1;
                        ListItem item = new ListItem(pageNumber.ToString());
                        if (i == gvCreatePass.PageIndex)
                        {
                            item.Selected = true;
                        }

                        topPageList.Items.Add(item);
                        bottomPageList.Items.Add(item);
                    }
                }

                if (topPageLabel != null && bottomPageLabel != null)
                {
                    topPageLabel.Text = bottomPageLabel.Text = " / " + gvCreatePass.PageCount.ToString();
                }
            }

            RegisterScriptCheckBoxHeader();
        }

        /// <summary>
        /// Đăng ký java script cho CheckBox Header trên GridView
        /// </summary>
        private void RegisterScriptCheckBoxHeader()
        {
            //Each time the data is bound to the grid we need to build up the CheckBoxIDs array
            //Get the header CheckBox
            CheckBox cbHeader = (CheckBox)gvCreatePass.HeaderRow.FindControl("HeaderLevelCheckBox");

            //Run the ChangeCheckBoxState client-side function whenever the
            //header checkbox is checked/unchecked
            cbHeader.Attributes["onclick"] = "ChangeAllCheckBoxStates(this.checked);";

            //Add the CheckBox's ID to the client-side CheckBoxIDs array
            List<string> ArrayValues = new List<string>();
            ArrayValues.Add(string.Concat("\"", cbHeader.ClientID, "\""));

            foreach (GridViewRow gvr in gvCreatePass.Rows)
            {
                //Get a programmatic reference to the CheckBox control
                CheckBox cb = (CheckBox)gvr.FindControl("RowLevelCheckBox");

                //If the checkbox is unchecked, ensure that the Header CheckBox is unchecked
                cb.Attributes["onclick"] = "ChangeHeaderAsNeeded();";

                //Add the CheckBox's ID to the client-side CheckBoxIDs array
                ArrayValues.Add(string.Concat("\"", cb.ClientID, "\""));
            }

            //Output the array to the Literal control (CheckBoxIDsArray)
            CheckBoxIDsArray.Text = "<script type=\"text/javascript\">" + string.Concat("var CheckBoxIDs =  [", string.Join(",", ArrayValues.ToArray()), "];") + "</script>";
        }

        protected void gvCreatePass_PageIndexChanged(object sender, EventArgs e)
        {
            gvCreatePass.SelectedIndex = -1;
        }
        #endregion

        protected void gvCreatePass_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                bool daKichHoat = Convert.ToBoolean(((HiddenField)e.Row.FindControl("hdfDaKichHoat")).Value);
                int isExists = Convert.ToInt32(((HiddenField)e.Row.FindControl("hdfIsExists")).Value);

                if (daKichHoat == true)
                    ((Label)e.Row.FindControl("lblDaKichHoat")).Text = "<img src=\"./Images/Icons/OK.gif\" alt=\"Đã kích hoạt\"  />";
                else
                    ((Label)e.Row.FindControl("lblDaKichHoat")).Text = "<img src=\"./Images/Icons/InValid.gif\" alt=\"Chưa kích hoạt\" />";

                if (isExists == 1)
                    ((Label)e.Row.FindControl("lblIsExists")).Text = "<img src=\"./Images/Icons/OK.gif\" alt=\"Đã tạo\"  />&nbsp;Đã tạo&nbsp;&nbsp;&nbsp;&nbsp;";
                else
                    ((Label)e.Row.FindControl("lblIsExists")).Text = "<img src=\"./Images/Icons/InValid.gif\" alt=\"Chưa tạo\" />&nbsp;Chưa tạo";
            }
            catch (Exception exc)
            { }
        }

        protected void btnKichHoat_Click(object sender, EventArgs e)
        {
            //Enumerate the GridViewRows
            for (int i = 0; i < gvCreatePass.Rows.Count; i++)
            {
                //Programmatically access the CheckBox from the TemplateField
                CheckBox cb = (CheckBox)gvCreatePass.Rows[i].FindControl("RowLevelCheckBox");
                HiddenField hdfIsExists = (HiddenField)gvCreatePass.Rows[i].FindControl("hdfIsExists");
                HiddenField hdfDaKichHoat = (HiddenField)gvCreatePass.Rows[i].FindControl("hdfDaKichHoat");
                HiddenField hdfMaSV = (HiddenField)gvCreatePass.Rows[i].FindControl("hdfMaSV");

                //If it's checked, delete it...
                if (cb.Checked
                    && Convert.ToInt32(hdfIsExists.Value) == 1
                    && Convert.ToBoolean(hdfDaKichHoat.Value) == false)
                {
                    QuyenDN.Update(hdfMaSV.Value.ToString(), true);
                }
            }

            LoadDataCaretePass();
        }

        protected void btnHuyKichHoat_Click(object sender, EventArgs e)
        {
            //Enumerate the GridViewRows
            for (int i = 0; i < gvCreatePass.Rows.Count; i++)
            {
                //Programmatically access the CheckBox from the TemplateField
                CheckBox cb = (CheckBox)gvCreatePass.Rows[i].FindControl("RowLevelCheckBox");
                HiddenField hdfIsExists = (HiddenField)gvCreatePass.Rows[i].FindControl("hdfIsExists");
                HiddenField hdfDaKichHoat = (HiddenField)gvCreatePass.Rows[i].FindControl("hdfDaKichHoat");
                HiddenField hdfMaSV = (HiddenField)gvCreatePass.Rows[i].FindControl("hdfMaSV");

                //If it's checked, delete it...
                if (cb.Checked
                    && Convert.ToInt32(hdfIsExists.Value) == 1
                    && Convert.ToBoolean(hdfDaKichHoat.Value) == true)
                {
                    QuyenDN.Update(hdfMaSV.Value.ToString(), false);
                }
            }

            LoadDataCaretePass();
        }

        protected void chkAllClass_CheckedChanged(object sender, EventArgs e)
        {
            ddlClass.Enabled = !chkAllClass.Checked;
        }

        protected void btnDeleteAllPass_Click(object sender, EventArgs e)
        {
            QuyenDN.DeleteAll();

            LoadDataCaretePass();
        }

    }
}